package com.biz.user.init;

import com.alibaba.fastjson.*;
import com.biz.user.designPattern.demo.*;
import lombok.extern.slf4j.*;
import org.springframework.boot.context.event.*;
import org.springframework.context.*;
import org.springframework.stereotype.*;

import java.util.*;
import java.util.function.*;

/**
 * @Description
 *       服务预热
 * @Author liuxi
 * @Date 2024/4/28
 **/
@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {

    Map<String, InitFunction> initFunctionMap = new HashMap<>();

    {
        initFunctionMap.put("预热fastjson", this::initFastJson);
    }

    /**
     * 服务启动时执行的任务
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        initFunctionMap.forEach((desc, function) -> {
            try {
                long start = System.currentTimeMillis();
                function.invoke();
                log.info("ApplicationInit{}.costTime{}", desc, System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("任务[{}]执行失败", desc, e);
            }
        });
    }

    private void initFastJson() {
        SkuDO skuDO = new SkuDO();
        skuDO.setSkuId(1L);
        skuDO.setSkuName("Apple");
        String s = JSON.toJSONString(skuDO);
        System.out.println(s);
        JSON.parseObject(s, SkuDO.class);
    }

    interface InitFunction {
        void invoke();
    }
}
